using System;
using System.IO;
using System.Xml.Serialization;

namespace CoreMobile.cfg
{
    public class SettingsManager<S> where S : AbstractSettings, new()
    {
        private static SettingsManager<S> localSettings = null;

        public S Settings
        {
            get { return settings; }
            set { settings = value; }
        }

        public static SettingsManager<S> get()
        {
            if(localSettings == null) localSettings=new SettingsManager<S>();

            return localSettings;
        }

        private string xmlPathFile ;
        private S settings;
        private XmlSerializer serializer;

        private SettingsManager()
        {
            serializer = new XmlSerializer(typeof(S));
            xmlPathFile = typeof(S).Name+ ".cfg.xml";
            this.loadFromXML();
        }

        private void loadFromXML()
        {


            try
            {
                var file = new FileStream(this.xmlPathFile, FileMode.Open);

                this.Settings = (S)serializer.Deserialize(file);

                file.Close();
            }
            catch (FileNotFoundException _)
            {
                this.settings = new S();
            }
        }

        public void save()
        {
            var writer = new StreamWriter(xmlPathFile,false);
            serializer.Serialize(writer, settings);
            writer.Close();
        }

    }
}